package com.tools;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;

import com.test.user;

/**
 * 反射应用
 */
public class ClassReflex {

    /*public static void main(String[] args) {
        try {
            user user1 = new user();
            final Class<? extends com.test.user> aClass = user1.getClass();

              Class<user> userClass = user.class;

            Class<?> forName = Class.forName("com.test.user");

            //通过反射获取到构造器并初始化
            Constructor<?> constructor = forName.getConstructor(String.class, String.class);

            constructor.setAccessible(true);  Object o1 = constructor.newInstance("xxxxx", "yyyyy");
            System.out.println(o1);

            //根据反射获取到方法，然后执行
            Method getUsername = forName.getDeclaredMethod("getUsername");
            getUsername.setAccessible(true);
             getUsername.invoke(o1);

             //获取含有入参的方法，第一个参数为方法名，后续参数为参数的实例
            //执行方法invoke  第一个方法为此对象，第二个对象参数
            Method setUserid = forName.getDeclaredMethod("setUserid", String.class);
            setUserid.setAccessible(true);
             setUserid.invoke(forName.newInstance(),"aa");



            //根据反射获取到参数 进行设置
            Field declaredField = forName.getDeclaredField("userid");
            declaredField.setAccessible(true);
            declaredField.set(o1, "123");
            if (o1 instanceof user) {
                user o11 = (user) o1;
                System.out.println(o11);
            }


            Object o = forName.newInstance();
             if (o instanceof user) {
                 user o2 = (user) o;
                 System.out.println(o2);
             }




         } catch (Exception e) {
            e.printStackTrace();
        }
    }*/

}
